<script setup lang="ts">
import { onShow, onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import wucTab from '@/components/wuc-tab.vue'
import type { CouponsItem, IcouponRective, ICouponPageParam } from '@/types/coupon'
import { pageCouponAPI, countAPI, receiveAPI } from '@/services/coupon'
import { useMemberStore } from '@/stores'
const { getUserInfo, setCouponCount } = useMemberStore()

const initParams: ICouponPageParam = {
  page: 1,
  limit: 10,
  userStatus: -1,
  userId: null,
}
const params = ref(initParams as ICouponPageParam)
const noMore = ref(false)
const couponsList = ref<CouponsItem[]>([])
const total = ref(0)
const finish = ref(false)

const tabList = ref([
  { name: '可领取', status: -1 },
  { name: '可使用', status: 0 },
  { name: '已使用', status: 1 },
  { name: '已过期', status: 2 },
])

const TabCur = ref(0)

const tabChange = async (index: any) => {
  console.log(index)
  TabCur.value = index
  params.value = {
    ...initParams,
    userStatus: tabList.value[index].status as number,
  }
  couponsList.value = []
  await request()
}

onLoad(async (e: any) => {
  console.log('ceshi', e)

  uni.startPullDownRefresh()
  await request()
})

const request = async () => {
  if (finish.value === true) {
    return
  }

  finish.value = true
  const res = await pageCouponAPI({ ...params.value, userId: getUserInfo()?.id })
  couponsList.value = [...couponsList.value, ...res.data.list]
  total.value = res.data.total
  finish.value = false
}

// 滚动触底
const onScrolltolower = async () => {
  if (finish.value === true) {
    return
  }
  if (couponsList.value.length < total.value) {
    params.value.page = params.value.page + 1
  } else {
    noMore.value = true
    return
  }
  await request()
}

const triggered = ref(false) // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发

const onPulling = (e: any) => {
  if (e.detail.deltaY < 50) return // 防止上滑页面也触发下拉
  triggered.value = true
}
// 自定义下拉刷新被复位
const onRestore = () => {
  triggered.value = false
}
// 自定义下拉刷新被中止
const onAbort = () => {
  console.error('onAbort')
}
// 自定义下拉刷新被触发
const onRefresh = async () => {
  if (finish.value === true) {
    return
  }
  couponsList.value = []
  params.value = {
    ...params.value,
    page: initParams.page,
    limit: initParams.limit,
  }
  await request()
  triggered.value = false
}

const receiveHandleTap = async (item: CouponsItem) => {
  // 领取优惠券
  if (params.value.userStatus === -1) {
    await receiveAPI({
      storeId: item.storeId,
      couponId: item.id,
      userId: getUserInfo()?.id,
      expireTime: item.validTo,
    })
    item.userStatus = 0
    setCouponCount(1)

    onRefresh()
  }

  if (params.value.userStatus === 0 && item.userStatus === 0) {
    uni.switchTab({
      url: '/pages/category/category',
      success: () => {
        console.log('success')
      },
    })
  }
}

const getBtnText = (record: any) => {
  const aa = [
    {
      status: null,
      text: '立即领取',
    },
    {
      status: 0,
      text: '立即使用',
    },
    {
      status: 1,
      text: '已使用',
    },
    {
      status: 2,
      text: '已过期',
    },
    {
      status: 3,
      text: '已失效',
    },
  ]
  if (params.value.userStatus === -1 && record.issuedQuantity < record.limitPerUser) {
    return '立即领取'
  }
  if (params.value.userStatus === 2) {
    return '已过期'
  }
  return aa.find((item) => item.status === record.userStatus)?.text
}
</script>

<template>
  <view class="coupon-page">
    <wuc-tab
      :tab-list="tabList"
      :tabCur="TabCur"
      tab-class="text-center bg-white wuc-tab fixed"
      select-class="text-blue"
      @change="tabChange"
    ></wuc-tab>
    <scroll-view
      class="coupon-main"
      v-if="couponsList?.length"
      scroll-y
      @scrolltolower="onScrolltolower"
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      :refresher-threshold="100"
      refresher-background="#F5F5F7"
      @refresherpulling="onPulling"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore"
      @refresherabort="onAbort"
    >
      <view class="coupon-list">
        <view
          class="coupon-item"
          v-for="item in couponsList"
          :key="item.id"
          :class="{
            green: params.userStatus === -1,
            gray: params.userStatus === 2,
            blur: params.userStatus === 1,
          }"
        >
          <view class="coupon-item-title">
            <view class="price">{{
              item.amount ? '¥' + item.amount : item.discountRate * 10 + '折'
            }}</view>
            <view class="desc">满{{ item.minAmount }}可用</view>
          </view>
          <view
            class="coupon-item-content"
            :class="{
              done: item.userStatus === 1,
              invalid: item.userStatus === 2 || item.userStatus === 3,
            }"
          >
            <view class="title">{{ item.couponName }}</view>
            <view class="time">{{ item.validFrom }}-{{ item.validTo }}</view>
            <view class="btn" @click="receiveHandleTap(item)">
              <text class="text">{{ getBtnText(item) }}</text>
            </view>
            <!-- <view class="btn active"><text class="text">已领取</text></view> -->
          </view>
        </view>

        <!-- <view class="coupon-item">
          <view class="coupon-item-title">
            <view class="price">¥30</view>
            <view class="desc">满100可用</view>
          </view>
          <view class="coupon-item-content done">
            <view class="title">新人专享券</view>
            <view class="time">2024.01.20-2024.02.20</view>
            <view class="btn"><text class="text">立即领取</text></view>
          </view>
        </view>
        <view class="coupon-item green">
          <view class="coupon-item-title">
            <view class="price">¥30</view>
            <view class="desc">满100可用</view>
          </view>
          <view class="coupon-item-content">
            <view class="title">新人专享券</view>
            <view class="time">2024.01.20-2024.02.20</view>
            <view class="btn"><text class="text">立即领取</text></view>
          </view>
        </view> -->
        <!--


        <view class="coupon-item green">
          <view class="coupon-item-title">
            <view class="price">¥30</view>
            <view class="desc">满100可用</view>
          </view>
          <view class="coupon-item-content">
            <view class="title">新人专享券</view>
            <view class="time">2024.01.20-2024.02.20</view>
            <view class="btn active"><text class="text">立即领取</text></view>
          </view>
        </view>

        <view class="coupon-item green">
          <view class="coupon-item-title">
            <view class="price">¥30</view>
            <view class="desc">满100可用</view>
          </view>
          <view class="coupon-item-content">
            <view class="title">新人专享券</view>
            <view class="time">2024.01.20-2024.02.20</view>
            <view class="btn"><text class="text">立即领取</text></view>
          </view>
        </view>

        <view class="coupon-item green">
          <view class="coupon-item-title">
            <view class="price">¥30</view>
            <view class="desc">满100可用</view>
          </view>
          <view class="coupon-item-content">
            <view class="title">新人专享券</view>
            <view class="time">2024.01.20-2024.02.20</view>
            <view class="btn"><text class="text">立即领取</text></view>
          </view>
        </view>

        <view class="coupon-item green">
          <view class="coupon-item-title">
            <view class="price">¥30</view>
            <view class="desc">满100可用</view>
          </view>
          <view class="coupon-item-content">
            <view class="title">新人专享券</view>
            <view class="time">2024.01.20-2024.02.20</view>
            <view class="btn"><text class="text">立即领取</text></view>
          </view>
        </view> -->
      </view>
    </scroll-view>
    <view v-else class="no-data coupon-main"><text>没有数据</text></view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
  background-color: $background-color;
}
.coupon-page {
  background-color: $background-color;
  height: 100%;
  display: flex;
  flex-direction: column;
  .coupon-main {
    flex: 1;
    .coupon-list {
      padding: 20px;

      .coupon-item {
        padding: $medium-padding;
        height: 248rpx;
        display: flex;
        flex-direction: row;
        margin-bottom: 20rpx;
        background-color: #fff;
        border-radius: $border-lager-radius;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);

        .coupon-item-title {
          display: flex;
          flex-direction: column;
          flex: 1;
          justify-content: center;
          border-right: 1px solid #f0f0f0;
          align-items: center;
          // padding: 15px;
          // background: linear-gradient(to right, #ff9999, #ff6666);
          // color: white;

          .price {
            font-size: 60rpx;
            color: #ff4444;
            font-weight: $font-bold-weight;
          }

          .desc {
            margin-top: 10rpx;
            font-size: 24rpx;
            color: #6b7280;
            font-weight: $font-regular-weight;
          }
        }

        .coupon-item-content {
          flex: 2;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          padding-left: 30rpx;

          &.invalid-done {
            position: relative;
            &::after {
              content: '\e666';
              font-family: 'iconfont' !important;
              color: $color;
              font-size: 110rpx;
              position: absolute;
              right: -10rpx;
              bottom: 0;
            }
          }
          &.done {
            position: relative;
            &::after {
              content: '\e648';
              font-family: 'iconfont' !important;
              color: $color;
              font-size: 100rpx;
              position: absolute;
              right: 0;
              bottom: 0;
            }
          }
          .title {
            font-size: $font-medium-size;
            font-weight: $font-medium-weight;
            color: #000;
          }

          .time {
            font-size: $font-small-size;
            color: #6b7280;
            font-weight: $font-medium-weight;
          }

          .btn {
            display: flex;
            .text {
              line-height: 72rpx;
              font-size: $font-size;
              color: #fff;
              background-color: #ff4444;
              border-radius: 36rpx;
              text-align: center;
              padding: 0 36rpx;
            }

            &.active {
              .text {
                background-color: #fff;
                color: #ff4444;
                border: 1px solid #ff4444;
              }
            }
          }
        }

        &.blur {
          .coupon-item-title {
            .price {
              color: $color;
            }
          }

          .coupon-item-content {
            .btn {
              .text {
                background-color: #fff;
                color: $color;
                border: 1px solid $color;
              }
            }
          }
        }

        &.gray {
          .coupon-item-title {
            .price {
              color: #888;
            }
          }

          .coupon-item-content {
            .btn {
              .text {
                background-color: #888;
              }

              &.active {
                .text {
                  background-color: #fff;
                  color: #888;
                  border: 1px solid #888;
                }
              }
            }
          }
        }

        &.green {
          .coupon-item-title {
            .price {
              color: #2e8b57;
            }
          }
          .coupon-item-content {
            .btn {
              .text {
                background-color: #2e8b57;
              }

              &.active {
                .text {
                  background-color: #fff;
                  color: #2e8b57;
                  border: 1px solid #2e8b57;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
